package com.aoyy.util;

import java.io.Serializable;
import java.sql.Types;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.usertype.UserType;
import org.hibernate.HibernateException;
/**==================================================================
 * <code>EnumType</code> class, one defined <code>Enum</code> utility.
 * @author Administrator
 * @date 2017-07-12
 * =================================================================== */
public class EnumType<T extends Enum<T>> implements UserType {
  private static final int[] SQL_TYPES = {Types.VARCHAR};
  private Class<T> clazz = null;
  
  public EnumType(Class<T> clazz) {
	this.clazz = clazz;  
  }
  
  @Override
  public Object assemble(Serializable arg0, Object arg1) throws HibernateException {
    return arg0;
  }

  @Override
  public Object deepCopy(Object arg0) throws HibernateException {
	return arg0;
  }

  @Override
  public Serializable disassemble(Object arg0) throws HibernateException {
    return (Serializable) arg0;
  }

  @Override
  public boolean equals(Object arg0, Object arg1) throws HibernateException {
    if (arg0 == arg1) {
      return true;	
    }
    if (arg0 == null || arg1 == null) {
      return true; 	
    }
	return arg0.equals(arg1);
  }

  @Override
  public int hashCode(Object arg0) throws HibernateException {
	if (arg0 != null) {
	  return arg0.hashCode();
	}
	return 0;
  }

  @Override
  public boolean isMutable() {
	return false;
  }

  @Override
  public Object nullSafeGet(ResultSet arg0, String[] arg1, SessionImplementor arg2, Object arg3)
			throws HibernateException, SQLException {
	try {
	  String name = arg0.getString(arg1[0]).toUpperCase();
	  return Enum.valueOf(clazz, name);
	} catch (Exception ex) {
	  ex.printStackTrace();	
	}
	return null;
  }

  @Override
  public void nullSafeSet(PreparedStatement arg0, Object arg1, int arg2, SessionImplementor arg3)
			throws HibernateException, SQLException {
	if (arg1 == null) {
	  arg0.setNull(arg2, Types.VARCHAR);	
	} else {
	  arg0.setString(arg2, ((Enum<?>)arg1).name());	
	}
  }

  @Override
  public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
    return arg0;
  }

  @Override
  public Class<T> returnedClass() {
    return clazz;
  }

  @Override
  public int[] sqlTypes() {
    return SQL_TYPES;
  }
  
}